var express = require('express');
var router = express.Router();
const moment = require('moment');
const AccountModel = require('../../models/AccountModel');
// 导入声明中间件检测登录
let checkLoginMiddleware = require('../../middlewares/checkLoginMiddleware')

// 添加首页路由规则
router.get('/', (req, res) => {
  // 重定向 /account
  res.redirect('/account')
})

// 记账本列表
router.get('/account', checkLoginMiddleware, function (req, res, next) {
  AccountModel.find().sort({ time: -1 }).exec((err, data) => {
    if (err) {
      res.status(500).send('读取失败~')
      return
    }
    res.render('list', { accounts: data, moment: moment })
  })
});

// 添加记录
router.get('/account/create', checkLoginMiddleware, function (req, res, next) {
  res.render('create')
})

// 新增记录
router.post('/account', checkLoginMiddleware, (req, res) => {
  AccountModel.create({
    ...req.body,
    time: moment(req.body.time).toDate()
  }, (err, data) => {
    if (err) {
      res.status(500).send('插入失败');
      return
    }
    res.render('success', { msg: '添加成功哦~', url: '/account' })
  })
})

// 删除记录
router.get('/account/:id', checkLoginMiddleware, (req, res) => {
  // 获取params的id参数
  let id = req.params.id
  // 删除
  AccountModel.deleteOne({ _id: id }, (err, data) => {
    if (err) {
      res.status(500).send('删除失败~')
      return
    }
    res.render('success', { msg: '删除成功~~~', url: '/account' })
  })
})
module.exports = router;
